const express = require("express");
const client = require("../client");
const router = express.Router();
let PQueue;
import("p-queue").then((module) => {
  PQueue = module.default;
});

// 异步获取队列（确保 PQueue 已加载）
async function getDownloadQueue() {
  if (!PQueue) {
    const module = await import("p-queue");
    PQueue = module.default;
  }
  return new PQueue({ concurrency: 1 });
}

router.get("/", async (req, res, next) => {
  try {
    let field_names = ["届数", "图片附件"];
    if (req.query.field_names) {
      field_names = field_names.concat(req.query.field_names.split(","));
    }
    let conditions = [];
    if (req.query.conditions) {
      conditions = JSON.parse(req.query.conditions);
    }
    const result = await client.bitable.appTableRecord.search({
      params: {
        page_size: req.query.page_size || 10,
        page_token: req.query.page_token || "",
      },
      path: {
        app_token: process.env.app_token,
        table_id: process.env.table_id,
      },
      data: {
        view_id: process.env.view_id,
        field_names: field_names,
        filter: {
          conjunction: "and",
          conditions: conditions,
        },
      },
    });
    result["access_token"] = await client.tokenManager.getTenantAccessToken();
    res.json(result);
  } catch (e) {
    console.log("这里有错误信息", e);
    res.json(result);
  }
});

router.get("/pic", async (req, res, next) => {
  try {
    // const result = await client.drive.v1.media.download({
    //   path: {
    //     file_token: req.query.file_token,
    //   },
    // });
    // const stream = await result.getReadableStream();
    // stream.pipe(res);
    const downloadQueue = await getDownloadQueue(); // 等待队列初始化
    const result = await downloadQueue.add(() =>
      client.drive.v1.media.download({
        path: {
          file_token: req.query.file_token,
        },
      })
    );

    const stream = await result.getReadableStream();
    stream.pipe(res);
  } catch (e) {
    console.log("请求错误", e);
    // res.json(result);
  }
});

router.get("/fields", async (req, res, next) => {
  try {
    const result = await client.bitable.v1.appTableField.list({
      path: {
        app_token: process.env.app_token,
        table_id: process.env.table_id,
      },
      params: {
        view_id: "vew61nj8v2",
        text_field_as_array: true,
      },
    });
    res.json(result);
  } catch (e) {
    console.log(e);
    res.json(result);
  }
});

module.exports = router;
